%test Propagacion
close all
clear variables
addpath(genpath('../'))
%matlabpool size;
%if (ans==0)
%    matlabpool open 2
%end

load wave.mat
M1=1;
N=32;
c=1500;
pitch=0.011/32;
efs=80*10^6;

pulso=ones(M1,N);
pulso=flipud(wave);
pulso=wave;
[M1,N]=size(wave);
minX=0;
maxX=32*pitch;
maxZ=0.1;
minZ=0.001;

zeros_end=ceil(efs*sqrt(maxX^2+maxZ^2)/c); %Máximo delay en muestras

%Extiendo pulso
newM1=M1+zeros_end;
newM1=2^(ceil(log(newM1)/log(2)));
newnewM1=newM1;
pulso_ext=zeros(newM1,N);
pulso_ext(1:M1,:)=pulso;
%Calculo fft de pulso extendido
Fpulso_ext=fft(pulso_ext);
Fpulso_ext=Fpulso_ext(1:(newM1/2+1),:);


ResX=64;
ResZ=1024;
DeltaX=maxX-minX;
DeltaZ=maxZ-minZ;

dX=DeltaX/ResX;
dZ=DeltaZ/ResZ;


E=zeros(ResX,ResZ,newnewM1);
for i=1:ResX
    i
    D=zeros(ResZ,newnewM1);
    for j=1:ResZ
        x=minX+(i-1)*dX;
        z=minZ+(j-1)*dZ;
        pulso_llegada=propagacion(pulso_ext,x,z,c,pitch,efs,Fpulso_ext,newnewM1);
        D(j,:)=pulso_llegada; %El abs sobra, debería ser real lo que se devuelve!
    end
    E(i,:,:)=D;
end


figure
hold on
subplot(2,3,1)
surf(abs(E(:,:,1)),'EdgeColor','none')
subplot(2,3,2)
surf(abs(E(:,:,100)),'EdgeColor','none')
subplot(2,3,3)
surf(abs(E(:,:,500)),'EdgeColor','none')
subplot(2,3,4)
surf(abs(E(:,:,1000)),'EdgeColor','none')
subplot(2,3,5)
surf(abs(E(:,:,1500)),'EdgeColor','none')
subplot(2,3,6)
surf(abs(E(:,:,4000)),'EdgeColor','none')
hold off


X=minX+[0:(ResX-1)]*dX;
Z=minZ+[0:(ResZ-1)]*dZ;
%aviobj = avifile('test1','compression','None','fps',5);
fig=figure;
for l=1:1:size(E,3)
    %Xn=[minX:dX/3:maxX];
    %Zn=[minZ:dZ/3:maxZ]';
    %aux=interp2(X,Z,E(:,:,l)',Xn,Zn);
    %figure
    image(X,Z,abs(E(:,:,l))) %Uniformizar colormap
    %image(Xn,Zn,abs(aux))
    caxis([0,100])
    F = getframe(fig);
    %aviobj = addframe(aviobj,F);
end
%close(fig);
%aviobj = close(aviobj);


fig=figure;
for l=1:16:size(E,2)
    %Xn=[minX:dX/3:maxX];
    %Zn=[minZ:dZ/3:maxZ]';
    %aux=interp2(X,Z,E(:,:,l)',Xn,Zn);
    figure
    image(X,Z,abs(reshape(E(:,l,:),size(E,1),size(E,3)))) %Uniformizar colormap
    %image(Xn,Zn,abs(aux))
    caxis([0,100])
    %F = getframe(fig);
    %aviobj = addframe(aviobj,F);
end


%aviobj = avifile('test2','compression','None','fps',15);
%fig=figure;
for l=1:1:size(E,3)
    %figure
    %Xn=[minX:dX/3:maxX];
    %Zn=[minZ:dZ/3:maxZ]';
    %aux=interp2(X,Z,E(:,:,l)',Xn,Zn);
    surf(X,Z,abs(E(:,:,l))','EdgeColor','none') %Uniformizar colormap
    %surf(Xn,Zn,abs(aux),'EdgeColor','none')
    axis([minX maxX minZ maxZ 0 100])
    caxis([0 100])
    F = getframe(fig);
    %aviobj = addframe(aviobj,F);
end
%close(fig);
%aviobj = close(aviobj);
    

%matlabpool close